package com.meichis.mcsappframework.widget;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.meichis.mcsappframework.adapter.pagertabstrip.PagerBottomAdapter;
import com.meichis.mcsappframework.adapter.pagertabstrip.PagerTabAdapter;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MCPagerTabStrip extends ViewGroup implements OnClickListener {

    private ViewPager mViewPager;
    private PagerAdapter pagerAdapter;
    private TextView[] textViews;
    private ImageView[] imageViews;
    private int[] resIds, selresIds;
    private ImageView.ScaleType scaleType;
    private DisplayImageOptions options;
    private int seltextColor = Color.BLACK;
    private int textColor = Color.LTGRAY;
    private int lineHeight = -1;
    private float lineWeight = -1;
    private float textSize = 16;
    private String[] description, resUrls, selresUrls;
    private View viewline;
    private int height, width, margin;
    private LayoutParams lp_parent;

    private ViewPager.OnPageChangeListener mlistener;

    public MCPagerTabStrip(Context context) {
        super(context);
    }

    public MCPagerTabStrip(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    /**
     * 设置下划线颜色
     *
     * @param color
     */
    public void setselColor(int color) {
        seltextColor = color;
    }

    /**
     * 设置文字大小
     *
     * @param color
     */
    public void setTextColor(int color) {
        textColor = color;
    }

    /**
     * 设置下划线高度
     *
     * @param height
     */
    public void setLineHeight(int height) {
        lineHeight = height;
    }

    /**
     * 设置下划线所占比例
     *
     * @return
     */
    public void setLineWeight(float lineWeight) {
        this.lineWeight = lineWeight;
    }

    /**
     * 设置文字大小
     *
     * @param size
     */
    public void setTextSize(float size) {
        textSize = size;
    }

    /**
     * 设置对应的ViewPager
     *
     * @param viewPager
     */
    public void setViewPager(ViewPager viewPager, PagerAdapter adapter, ViewPager.OnPageChangeListener listener) {
        mViewPager = viewPager;
        mlistener = listener;
        pagerAdapter = adapter;
        lp_parent = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        if (pagerAdapter != null) {
            viewPager.setAdapter(adapter);
            if (pagerAdapter instanceof PagerTabAdapter) {//文字标题，View内容
                textViews = new TextView[pagerAdapter.getCount()];
                for (int i = 0; i < pagerAdapter.getCount(); i++) {
                    textViews[i] = new TextView(getContext());
                    textViews[i].setLayoutParams(lp_parent);
                    textViews[i].setGravity(Gravity.CENTER);
                    textViews[i].setSingleLine(true);
                    textViews[i].setTextSize(textSize);
                    if (i < textViews.length) {
                        if (i == mViewPager.getCurrentItem()) {
                            textViews[i].setTextColor(seltextColor);
                        } else {
                            textViews[i].setTextColor(textColor);
                        }
                        textViews[i].setText(pagerAdapter.getPageTitle(i));
                    }
                    textViews[i].setOnClickListener(this);
                    addView(textViews[i]);

                }
                //文字标题，View内容 默认有下划线
                if (lineHeight == -1) setLineHeight(3);
                if (lineWeight == -1) setLineWeight(pagerAdapter.getCount() > 3 ? 1 : 0.75f);
            }
            if (pagerAdapter instanceof PagerBottomAdapter) {//图片标题，Fragment内容
                resIds = ((PagerBottomAdapter) pagerAdapter).getResIds();
                selresIds = ((PagerBottomAdapter) pagerAdapter).getSelresIds();
                resUrls = ((PagerBottomAdapter) pagerAdapter).getResUrls();
                selresUrls = ((PagerBottomAdapter) pagerAdapter).getSelresUrls();
                description = ((PagerBottomAdapter) pagerAdapter).getDescription();
                scaleType = ((PagerBottomAdapter) pagerAdapter).getScaleType();
                options = ((PagerBottomAdapter) pagerAdapter).getOptions();
                if (resUrls != null && selresUrls != null || (resIds != null && selresIds != null)) {
                    imageViews = new ImageView[pagerAdapter.getCount()];
                }
                if (description != null) {
                    textViews = new TextView[pagerAdapter.getCount()];
                }
                for (int i = 0; i < pagerAdapter.getCount(); i++) {
                    if (imageViews != null) {
                        imageViews[i] = new ImageView(getContext());
                        if (scaleType != null)
                            imageViews[i].setScaleType(scaleType);
                        if (i == mViewPager.getCurrentItem()) {
                            setImageSelResource(i);
                        } else {
                            setImageResource(i);
                        }
                        imageViews[i].setOnClickListener(this);
                        addView(imageViews[i]);
                    }
                    if (textViews != null) {
                        textViews[i] = new TextView(getContext());
                        if (imageViews == null)
                            textViews[i].setLayoutParams(lp_parent);
                        textViews[i].setGravity(Gravity.CENTER);
                        textViews[i].setSingleLine(true);
                        textViews[i].setTextSize(textSize);
                        if (i < description.length)
                            textViews[i].setText(description[i]);
                        if (i == mViewPager.getCurrentItem()) {
                            textViews[i].setTextColor(seltextColor);
                        } else {
                            textViews[i].setTextColor(textColor);
                        }
                        textViews[i].setOnClickListener(this);
                        addView(textViews[i]);
                    }
                }
            }

            if (lineHeight > 0 && lineWeight > 0) {
                viewline = new View(getContext());
                viewline.setBackgroundColor(seltextColor);
                addView(viewline);
            }
            mViewPager.addOnPageChangeListener(PageListener);
        }
    }

    private void setImageResource(int i) {
        if (resUrls == null) {
            if (i < resIds.length)
                imageViews[i].setImageResource(resIds[i]);
        } else {
            if (i < resUrls.length)
                ImageLoader.getInstance().displayImage(resUrls[i], imageViews[i]);
        }
    }

    private void setImageSelResource(int i) {
        if (selresUrls == null) {
            if (i < selresIds.length)
                imageViews[i].setImageResource(selresIds[i]);
        } else {
            if (i < selresUrls.length)
                ImageLoader.getInstance().displayImage(selresUrls[i], imageViews[i], options);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = measureWidth(widthMeasureSpec);
        int measureHeight = measureHeight(heightMeasureSpec);
        // 计算自定义的ViewGroup中所有子控件的大小
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        // 设置自定义的控件MyViewGroup的大小
        setMeasuredDimension(measureWidth, measureHeight);
    }

    private int measureWidth(int pWidthMeasureSpec) {
        int result = 0;
        int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);// 得到模式
        int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);// 得到尺寸

        switch (widthMode) {
            /**
             * mode共有三种情况，取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY,
             * MeasureSpec.AT_MOST。
             *
             *
             * MeasureSpec.EXACTLY是精确尺寸，
             * 当我们将控件的layout_width或layout_height指定为具体数值时如andorid
             * :layout_width="50dip"，或者为FILL_PARENT是，都是控件大小已经确定的情况，都是精确尺寸。
             *
             *
             * MeasureSpec.AT_MOST是最大尺寸，
             * 当控件的layout_width或layout_height指定为WRAP_CONTENT时
             * ，控件大小一般随着控件的子空间或内容进行变化，此时控件尺寸只要不超过父控件允许的最大尺寸即可
             * 。因此，此时的mode是AT_MOST，size给出了父控件允许的最大尺寸。
             *
             *
             * MeasureSpec.UNSPECIFIED是未指定尺寸，这种情况不多，一般都是父控件是AdapterView，
             * 通过measure方法传入的模式。
             */
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = widthSize;
                break;
        }
        return result;
    }

    private int measureHeight(int pHeightMeasureSpec) {
        int result = 0;

        int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
        int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);

        switch (heightMode) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.EXACTLY:
                result = heightSize;
                break;
        }
        return result;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (pagerAdapter != null && pagerAdapter.getCount() > 0) {
            height = getMeasuredHeight();
            width = getMeasuredWidth() / pagerAdapter.getCount();
            margin = (int) (width - width * lineWeight);
            int paddingTop = getPaddingTop();
            int paddingBottom = getPaddingBottom();

            if (textViews != null && imageViews == null) {
                for (int i = 0; i < pagerAdapter.getCount(); i++) {
                    textViews[i].layout(width * i, paddingTop, width * i + width, height - paddingBottom);
                }
            } else if (textViews == null && imageViews != null) {
                for (int i = 0; i < pagerAdapter.getCount(); i++) {
                    imageViews[i].layout(width * i, paddingTop, width * i + width, height - paddingBottom);
                }
            } else if (textViews != null && imageViews != null) {
                for (int i = 0; i < pagerAdapter.getCount(); i++) {
                    imageViews[i].layout(width * i, paddingTop, width * i + width, (height - paddingTop - paddingBottom) * 2 / 3 + paddingTop);
                    textViews[i].layout(width * i, (height - paddingTop - paddingBottom) * 2 / 3 + paddingTop, width * i + width, height - paddingBottom);
                }
            }
            if (viewline != null)
                viewline.layout(width * mViewPager.getCurrentItem() + margin, height - lineHeight, width * mViewPager.getCurrentItem() + width - margin, height);
        }
    }

    ViewPager.OnPageChangeListener PageListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            if (textViews != null && textViews.length > 0) {
                for (int i = 0; i < textViews.length; i++) {
                    if (arg0 == i) {
                        textViews[i].setTextColor(seltextColor);
                    } else {
                        textViews[i].setTextColor(textColor);
                    }
                }
            }
            if (imageViews != null && imageViews.length > 0) {
                for (int i = 0; i < imageViews.length; i++) {
                    if (arg0 == i) {
                        setImageSelResource(i);
                    } else {
                        setImageResource(i);
                    }
                }
            }
            if (viewline != null)
                viewline.layout(width * arg0 + margin, height - lineHeight, width * arg0 + width - margin, height);
            //执行传递过来的listener
            if (mlistener != null) {
                mlistener.onPageSelected(arg0);
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            //执行传递过来的listener
            if (mlistener != null) {
                mlistener.onPageScrolled(arg0, arg1, arg2);
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            //执行传递过来的listener
            if (mlistener != null) {
                mlistener.onPageScrollStateChanged(arg0);
            }
        }
    };

    @Override
    public void onClick(View v) {
        if (textViews != null && textViews.length > 0) {
            if (textViews[mViewPager.getCurrentItem()] == v) {//虽然mViewPager.setCurrentItem(i)中设置还是当前页的话，不会执行pagechanger，但是预防万一
                return;
            }
            for (int i = 0; i < textViews.length; i++) {
                if (textViews[i] == v) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }
        if (imageViews != null && imageViews.length > 0) {
            if (imageViews[mViewPager.getCurrentItem()] == v) {//虽然mViewPager.setCurrentItem(i)中设置还是当前页的话，不会执行pagechanger，但是预防万一
                return;
            }
            for (int i = 0; i < imageViews.length; i++) {
                if (imageViews[i] == v) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }
    }
}